package com.worksystem.entity;

import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class BaseMapper<E> implements RowMapper<E> {

	private Class<E> entityClass;
	public BaseMapper(Class<E> entityClass) {
		this.entityClass=entityClass;
	}
	@Override
	public E mapRow(ResultSet rs, int rowNum) throws SQLException {
		E entity=null;
		//反射构造
		try {
			entity = entityClass.newInstance();
		} catch (InstantiationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Method[] methods =  entityClass.getMethods();
        for (Method method : methods) 
        { 
            try 
            { 
                if (method.getName().startsWith("set")) 
                { 
                    String field = method.getName(); 
                    field = field.substring(field.indexOf("set") + 3); 
                    field = field.toLowerCase().charAt(0) + field.substring(1); 
                    //有该字段再进行反射
                    if(rs.getObject(field) != null){
                    	method.invoke(entity, new Object[] 
                                { 
                                    rs.getObject(field)
                                }); 
                    }
                } 
            } 
            catch (Exception e) 
            { 
            } 
        } 
        System.out.println(entity);
		return entity;
	}

}
